package com.will.server;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 杨明智
 * @version:1.0
 * @create 2018年12月29日 9:59 AM
 * @description 保存客户端的SocketChannel, 客户端的Id作为Map的key
 **/
public class NettyChannelMap {
    private static Map<String,SocketChannel> map = new ConcurrentHashMap<>();

    public static void add(String clientId,SocketChannel socketChannel){
        map.put(clientId,socketChannel);
    }

    public static Channel get(String clientId){
        return map.get(clientId);
    }

//    public static void remove(SocketChannel socketChannel){
//        for (Map.Entry entry:map.entrySet()){
//            if (entry.getValue()==socketChannel){
//                map.remove(entry.getKey());
//            }
//        }
//    }

    public static void remove(SocketChannel socketChannel) {
        map.entrySet().stream().filter(entry -> entry.getValue() == socketChannel).forEach(entry -> map.remove(entry.getKey()));
    }

    public static void pushMsg2AllClient(String str){
        if(map.size()==0)
            return;
        for(SocketChannel socketChannel : map.values()){
            socketChannel.writeAndFlush(str);
        }
    }

    public static void pushMsg2Client(String id,String str){
        if(map.size()==0)
            return;
        SocketChannel socketChannel = map.get(id);
        socketChannel.writeAndFlush(str);
    }
}
